#include <dirent.h>
#include <string.h>
#include <stdio.h>

#include "filmbaza.h"
#include "scan.h"


#ifdef __unix__

const char ext[][5] = {
	"AAF",
	"AVI",
	"3GP",
	"ASF",
	"FLV",
	"M1V",
	"M2V",
	"FLA",
	"M4V",
	"MKV",
	"MOV",
	"MPEG",
	"MPG",
	"MPE",
	"MP4",
	"NSV",
	"SMI",
	"SWF",
	"WMV",
};

/**
 * @brief scan recursive scan all directories for files with video extension 
 * @param fb wskaźnik do bazy danych
 * @param path ścieżka do katalogu do przeskanowania
 */
void scan(struct filmbaza *fb, std::string path)
{
	DIR *dir;
	struct dirent *dp;
	
	dir = opendir(path.c_str());
	if ( !dir ) return;
	
	using namespace std;
		
	
	while ( ( dp = readdir(dir) ) ) {
		
		if ( dp->d_type == DT_DIR ) {
			/* its a directory to scan */
			std::string fn;
			
			/* get rid of '.' and '..' */
			if ( !strcmp(dp->d_name, ".") || !strcmp (dp->d_name, "..") )
				continue;
			
			fn = path + '/' + dp->d_name + '/';
			scan(fb, fn.c_str());
			
			
		} else {
			/* its a regular file, or whatever */
			const int len = sizeof(ext)/sizeof(*ext);
			char *p;
			int i;
			
			p = strrchr(dp->d_name, '.');
			if ( !p )
				continue;
			p += 1; /* we dont want the '.' in string */
			for (i = 0; i < len; ++i) {
				if ( !strcasecmp(p, ext[i]) ) {
					std::string name = dp->d_name;
					filmbaza_add(fb, name);
				}
			}
		}
		
	}
	
	closedir(dir);
}

#elif _WIN32

void scan(struct filmbaza *fb, std::string path)
{
	filmbaza_add(fb, "Scanning supported only on linux machines.");
}

#endif
